import { Context, Next } from "koa"
import redis from '../db/redis'
import Games from '../models/games'
import User from "../models/gptUser"

class GameController {
    // 新建游戏
    async createGame(ctx: Context, next: Next) {
        const { name, desc, route, icon, sort, play_method } = ctx.request.body;
        ctx.verifyParams({
            name: {
                type: 'string'
            },
            desc: {
                type: 'string'
            },
            route: {
                type: 'string'
            },
            icon: {
                type: 'string'
            },
            play_method: {
                type: 'string',
                required: false
            },
            sort: {
                type: 'number',
                required: false
            },
        })
        const isFind = await Games.findOne({ name })
        if (isFind) {
            ctx.throw('游戏名已存在')
        } else {
            const data = await Games.create({ name, desc, icon, route, sort, play_method })
            ctx.body = data
        }
        next()
    }
    // 获取游戏列表
    async getGameList(ctx: Context, next: Next) {
        const list = await Games.find({}).sort({updatedAt:-1})
        ctx.body = list
        next()
    }
    // 设置分数
    async setScore(ctx: Context, next: Next) {
        const { score, game_id, label } = ctx.request.body;
        ctx.verifyParams({
            score: {
                type: "number",
            },
            game_id: {
                type: "string",
            },
            label: {
                type: "string",
            },
        })
        console.log({ ...ctx.userInfo, score });
        const _score = await redis.zscore(`game:${game_id}`, ctx.userInfo._id)
        if (!_score || score > _score) {
            await redis.zadd(`game:${game_id}`, score, ctx.userInfo._id)
        }
        ctx.body = {}
        next()
    }
    // 获取游戏排行榜
    async getGameRank(ctx: Context, next: Next) {
        const { game_id, page = 1, size = 20 } = ctx.request.query
        ctx.verifyParams({
            game_id: {
                type: "string",
            }
        })
        const list = await redis.zrevrange(`game:${game_id}`, (Number(page) - 1) * Number(size), Number(page) * Number(size), "WITHSCORES")

        const members: any[] = [];
        list.forEach((_item, _index) => {
            if (_index % 2 === 0) {
                members.push({ label: '0', num: _index / 2 + 1, _id: _item })
            } else {
                members[members.length - 1].label = _item
            }
        })
        const users = await User.find({ _id: { $in: members.map(item => item._id) } }, { avatar: 1, name: 1 }).lean()
        const data = members.map((item, index) => ({ ...item, ...users[index] }))
        const total = await redis.zcard(`game:${game_id}`)
        ctx.body = { list: data, page, size, total }
        next()
    }
}
export default new GameController()